package cn.sxw.android.base.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Base64;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.zcs.autolayout.config.AutoLayoutConfig;
import com.zcs.autolayout.utils.AutoUtils;

import java.io.File;

/**
 * Created by ZengCS on 2019/5/28.
 * E-mail:zcs@sxw.cn
 * Add:成都市天府软件园E3-3F
 */
public class GlideStaticUtils {
    private static final String TAG = "GlideStaticUtils";

    public static void displayImage(String url, int defaultImage, ImageView imageView) {
        loadNormal(imageView.getContext(), url, defaultImage, imageView);
    }

    public static void displayImage(Context context, String imageUrl, ImageView imageView, int defaultImage) {
        loadNormal(context, imageUrl, defaultImage, imageView);
    }

    private static void loadNormal(final Context ctx, final String url, int placeholder, ImageView imageView) {
        JLogUtil.w(TAG, "loadNormal() called with: url = [" + url + "]");
        Glide.with(ctx).load(url).dontAnimate().placeholder(placeholder).diskCacheStrategy(DiskCacheStrategy.RESOURCE).listener(new RequestListener<Drawable>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                JLogUtil.e("Glide加载图片失败 --> " + url);
                JLogUtil.e(e);
                return false;
            }

            @Override
            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                return false;
            }
        }).into(imageView);
    }

    public static void displayCircleImage(String url, int defaultImage, ImageView imageView) {
        JLogUtil.w(TAG, "displayCircleImage() called with: url = [" + url + "]");
        Glide.with(imageView.getContext()).load(url).placeholder(defaultImage)
                .transform(new CircleCrop())
                .error(defaultImage)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .into(imageView);
    }

    /**
     * 加载圆角图片，默认CenterCrop，默认圆角10px
     */
    public static void displayRoundedImage(String url, int defaultImage, ImageView imageView) {
        JLogUtil.w(TAG, "displayRoundedImage() called with: url = [" + url + "]");
        displayRoundedImage(url, defaultImage, imageView, true, AutoUtils.getPercentWidthSize(10));
    }
    /**
     * 加载圆角图片，默认CenterCrop，默认圆角10px
     */
    public static void displayRoundedImage(Uri uri, int defaultImage, ImageView imageView) {
        JLogUtil.w(TAG, "displayRoundedImage() called with: uri = [" + uri + "]");
        displayRoundedImage(uri, defaultImage, imageView, true, AutoUtils.getPercentWidthSize(10));
    }

    /**
     * 加载圆角图片
     */
    public static void displayRoundedImage(Uri uri, int defaultImage, ImageView imageView, boolean centerCrop, int radius) {
        if (centerCrop) {
            Glide.with(imageView.getContext()).load(uri)
                    .placeholder(defaultImage)
                    .dontAnimate()
                    .apply(new RequestOptions().transform(new CenterCrop(), new RoundedCorners(radius)))
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .into(imageView);
        } else {
            Glide.with(imageView.getContext()).load(uri)
                    .placeholder(defaultImage)
                    .dontAnimate()
                    .transform(new RoundedCorners(radius))
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .into(imageView);
        }
    }

    /**
     * 加载圆角图片
     */
    public static void displayRoundedImage(String url, int defaultImage, ImageView imageView, boolean centerCrop, int radius) {
        if (centerCrop) {
            Glide.with(imageView.getContext()).load(url)
                    .placeholder(defaultImage)
                    .dontAnimate()
                    .apply(new RequestOptions().transform(new CenterCrop(), new RoundedCorners(radius)))
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .into(imageView);
        } else {
            Glide.with(imageView.getContext()).load(url)
                    .placeholder(defaultImage)
                    .dontAnimate()
                    .transform(new RoundedCorners(radius))
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .into(imageView);
        }
    }

    /**
     * 加载Base64位图片资源
     *
     * @param ctx
     * @param url
     * @param placeholder
     * @param imageView
     */
    public static void displayBase64Image(final Context ctx, String url, int placeholder, ImageView imageView) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        byte[] decode = null;
        url = url.split(",")[1];
        decode = Base64.decode(url, Base64.DEFAULT);
        Glide.with(ctx)
                .asBitmap()
                .load(decode)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .placeholder(placeholder)
                .dontAnimate()
                .into(imageView);
    }

    public static void loadPicAsBitmap(Context context, String url, SimpleTarget<Bitmap> listener) {
        Glide.with(context)
                .asBitmap()
                .load(url)
                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                .into(listener);
    }

    public static void loadPicAsBitmapNoCache(Context context, String url, SimpleTarget<Bitmap> listener) {
        Glide.with(context)
                .asBitmap()
                .load(url)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(listener);
    }

    /**
     * 下载资源
     *
     * @param context
     * @param url
     * @param listener
     */
    public static void loadPicAsFile(Context context, String url, SimpleTarget<File> listener) {
        Glide.with(context)
                .load(url)
                .downloadOnly(listener);
    }


    /**
     * 检查bitmap的尺寸，过大时在部分机型中无法加载
     *
     * @param resource
     * @return
     */
    public static Bitmap checkBitmapSize(Bitmap resource) {
        if (resource != null) {
            //长宽有一个超过屏幕相应尺寸的2.5倍时，进行缩放
            //setImageBitmap bitmap的尺寸过大时在部分机型（如：T3）会无法加载，所以需要进行缩放
            float maxRatio;
            if ("HUAWEI".equalsIgnoreCase(Build.BRAND) || "samsung".equalsIgnoreCase(Build.BRAND)) {
                maxRatio = 2.5f;
            } else {
                maxRatio = 2.0f;
            }
            float maxWidth = AutoLayoutConfig.getInstance().getScreenWidth() * maxRatio;
            float maxHeight = AutoLayoutConfig.getInstance().getScreenHeight() * maxRatio;
            //有一个尺寸超过最大尺寸，则进行缩放
            if (resource.getHeight() >= maxHeight || resource.getWidth() >= maxWidth) {
                float scale = Math.min(maxWidth / resource.getWidth(), maxHeight / resource.getHeight());
                Matrix matrix = new Matrix();
                matrix.setScale(scale, scale);
                resource = Bitmap.createBitmap(resource, 0, 0, resource.getWidth(), resource.getHeight(), matrix, false);
            }
        }
        return resource;
    }
}
